import React from 'react'

import SearchHeader  from '@/components/SearchHeader'

import HouseItem  from '@/components/HouseItem'

import Sticky  from '@/components/Sticky'

import NoHouse  from '@/components/NoHouse'

import API from '@/utils/api'

import { BASE_URL } from '@/utils/url'

import { Flex, Toast} from 'antd-mobile'

import { List, AutoSizer, WindowScroller, InfiniteLoader } from 'react-virtualized'

import styles from './index.module.css'

import Filter from './components/Filter'

//获取当前定位城市信息
// const {label:curCityName,value: id}=JSON.parse(localStorage.getItem('hkzf_city'))

export default class HouseList extends React.Component{

    state={
        //列表数据
        list: [],
        //总条数
        count: 0,
        //数据是否加载中
        isLoading: false
    }

    curCityName=''

    id=''

    //初始化实例属性
    filters={}

    //接受Filters组件中筛选条件数据
    onFilter = (filters)=>{
        //返回页面顶部
        window.scrollTo(0,0)
        this.filters = filters
        //点击保存获取房屋数据
        this.searchHouseList()
    }

    //来获取房屋列表数据
    async searchHouseList(){
      this.setState({
        isLoading: true
      })
        //获取当前定位城市id
        // 开启loading
        Toast.loading('加载中...', 0, null, false)
        const {data: {body: {count,list}}} = await API.get('/houses',{params:{
            cityId: this.id,
            ...this.filters,
            start: 1,
            end: 20
        }})
        Toast.hide()

        // 提示房源数量
        if(count){
          Toast.info(`共找到 ${count} 套房源`, 2, null, false)
        }

        this.setState({
            count: count,
            list: list,
            isLoading: false
        })
    }

    componentDidMount(){
      const {label:curCityName,value: id}=JSON.parse(localStorage.getItem('hkzf_city')||'{}')
      this.curCityName=curCityName
      this.id=id
        this.searchHouseList()
    }

    
    componentWillUnmount = () => {
      this.setState = (state,callback)=>{
        return;
      };
    }

    //渲染每一行数据的渲染函数
    //函数的返回值就表示最终渲染在页面的内容
    renderHouseList=({
        key,
        index,//索引号
        style //指定每一行的位置
    })=>{
        //根据索引号来获取当前这一行的房屋数据
        const { list } = this.state
        const { history } = this.props
        const house = list[index]
         // 判断 house 是否存在
        // 如果不存在，就渲染 loading 元素占位
        if(!house){
          return (
            <div key={key} style={style}>
              <p className={styles.loading}></p>
            </div>
          )
        }
        const { houseCode: id } = house
        return (
            <HouseItem 
              onClick={() => history.push(`/detail/${id}`)}
              key={key} 
              style={style}
              src={BASE_URL+house.houseImg}
              title={house.title}
              desc={house.desc}
              tags={house.tags}
              price={house.price}
            >
            </HouseItem>
        )
    }

    // 判断列表中的每一行是否加载完成
    isRowLoaded = ({ index }) => {
      return !!this.state.list[index]
    }

    // 用来获取更多房屋列表数据
    // 注意：该方法的返回值是一个 Promise 对象，并且，这个对象应该在数据加载完成时，来调用 resolve 让Promise对象的状态变为已完成。
    loadMoreRows = ({ startIndex, stopIndex }) => {
      const {list}=this.state
      return new Promise(resolve=>{
      //数据加载完成时调用resolve方法
         API.get('/houses',{params:{
            cityId: this.id,
            ...this.filters,
            start: startIndex,
            end: stopIndex
          }}).then(res=>{
            let newList=[...list,...res.data.body.list]
            this.setState({
              list: newList
            })
            //数据加载完成时调用resolve
            resolve()
          })
        })
      }

    renderList(){
      const {count,list,isLoading}=this.state
      const is=list.length
      if(!is&&!isLoading){
        return <NoHouse>没有找到房源，请您换个搜索条件吧~</NoHouse>
      }
      return (
        <div className={styles.houseItems}>
            {/* 房屋列表内容 */}
            <InfiniteLoader
              isRowLoaded={this.isRowLoaded}
              loadMoreRows={this.loadMoreRows}
              rowCount={count}
            >
              {({ onRowsRendered, registerChild })=>(
                  <WindowScroller>
                  {({height, isScrolling, scrollTop}) => (
                      <AutoSizer>
                          {({width})=>(
                              <List 
                              onRowsRendered={onRowsRendered}
                              ref={registerChild}
                              autoHeight //设置高度为WindowScroller最终列表渲染高度
                              width={width} //视口的宽度
                              height={height}//视口的高度
                              //修改List组件的rowCount为cityIndex数组的长度
                              rowCount={count}//List列表项的行数
                              rowHeight={120}//每一行的高度
                              rowRenderer={this.renderHouseList}//渲染列表项的每一行
                              isScrolling={isScrolling}
                              scrollTop={scrollTop}
                              />
                          )}
                      </AutoSizer>
                    )}
                  </WindowScroller>
                )}
            </InfiniteLoader>
        </div>
      )
    }

    render(){
        return (
            <div className={styles.root}>
                {/* 顶部搜索导航栏 */}
                <Flex className={styles.header}>
                    <i className="iconfont icon-back" onClick={()=>this.props.history.go(-1)}></i>
                    <SearchHeader curCityName={this.curCityName} className={styles.searchHeader}/>
                </Flex>
                {/* 条件筛选栏 */}
                <Sticky height={40}>
                  <Filter onFilter={this.onFilter}/>
                </Sticky>
                {/* 房屋列表 */}
                {this.renderList()}
            </div>
        )
    }
}

